import json
import os
import time
from urllib.request import urlopen

from aliyunsdkalidns.request.v20150109.DescribeSubDomainRecordsRequest import DescribeSubDomainRecordsRequest
from aliyunsdkcore.client import AcsClient

ipv4_flag = 1  # 是否开启ipv4 ddns解析,1为开启，0为关闭
ipv6_flag = 0  # 是否开启ipv6 ddns解析,1为开启，0为关闭

accessKeyId = ""  # 将accessKeyId改成自己的accessKeyId
accessSecret = ""  # 将accessSecret改成自己的accessSecret

ipv4s = {
    "demo1.com": ["@", "i", "www"],
    "demo2.com": ["@", "www"],
}
ipv4s_items = ipv4s.items()

ipv6s = {
    "demo1.com": ["ipv6"],
    "demo2.com": ["ipv6"],
}
ipv6s_items = ipv6s.items()

client = AcsClient(accessKeyId, accessSecret, 'cn-hangzhou')

print("execution time：%s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))


def update(RecordId, RR, Type, Value):  # 修改域名解析记录
    from aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest
    request = UpdateDomainRecordRequest()
    request.set_accept_format('json')
    request.set_RecordId(RecordId)
    request.set_RR(RR)
    request.set_Type(Type)
    request.set_Value(Value)
    client.do_action_with_exception(request)


def add(DomainName, RR, Type, Value):  # 添加新的域名解析记录
    from aliyunsdkalidns.request.v20150109.AddDomainRecordRequest import AddDomainRecordRequest
    request = AddDomainRecordRequest()
    request.set_accept_format('json')
    request.set_DomainName(DomainName)
    request.set_RR(RR)  # https://blog.zeruns.tech
    request.set_Type(Type)
    request.set_Value(Value)
    client.do_action_with_exception(request)


# 更新域名ipv4
def set_ipv4(request, domain, sub, ipv4):
    request.set_SubDomain(sub + '.' + domain)
    response = client.do_action_with_exception(request)  # 获取域名解析记录列表
    domain_list = json.loads(response)  # 将返回的JSON数据转化为Python能识别的
    print("获取到IPv4地址：%s" % ipv4)

    if domain_list['TotalCount'] == 0:
        add(domain, sub, "A", ipv4)
        print("新建域名解析成功")
    elif domain_list['TotalCount'] == 1:
        if domain_list['DomainRecords']['Record'][0]['Value'].strip() != ipv4.strip():
            update(domain_list['DomainRecords']['Record'][0]['RecordId'], sub, "A", ipv4)
            print("修改域名解析成功")
        else:
            print("IPv4地址没变")
    elif domain_list['TotalCount'] > 1:
        from aliyunsdkalidns.request.v20150109.DeleteSubDomainRecordsRequest import DeleteSubDomainRecordsRequest

        request = DeleteSubDomainRecordsRequest()
        request.set_accept_format('json')
        request.set_DomainName(domain)  # https://blog.zeruns.tech
        request.set_RR(sub)
        request.set_Type("A")
        client.do_action_with_exception(request)
        add(domain, sub, "A", ipv4)
        print("修改域名解析成功")


# 更新域名ipv6
def set_ipv6(request, domain, sub, ipv6):
    request.set_SubDomain(sub + '.' + domain)
    response = client.do_action_with_exception(request)  # 获取域名解析记录列表
    domain_list = json.loads(response)  # 将返回的JSON数据转化为Python能识别的

    print("获取到IPv6地址：%s" % ipv6)

    if domain_list['TotalCount'] == 0:
        add(domain, sub, "AAAA", ipv6)
        print("新建域名解析成功")
    elif domain_list['TotalCount'] == 1:
        if domain_list['DomainRecords']['Record'][0]['Value'].strip() != ipv6.strip():
            update(domain_list['DomainRecords']['Record'][0]['RecordId'], sub, "AAAA", ipv6)
            print("修改域名解析成功")
        else:  # https://blog.zeruns.tech
            print("IPv6地址没变")
    elif domain_list['TotalCount'] > 1:
        from aliyunsdkalidns.request.v20150109.DeleteSubDomainRecordsRequest import DeleteSubDomainRecordsRequest
        request = DeleteSubDomainRecordsRequest()
        request.set_accept_format('json')
        request.set_DomainName(domain)
        request.set_RR(sub)  # https://blog.zeruns.tech
        request.set_Type("AAAA")
        client.do_action_with_exception(request)
        add(domain, sub, "AAAA", ipv6)
        print("修改域名解析成功")


# 读取缓存的ip
def get_tag(tag_file):
    ls = "/tmp/" + tag_file + ".ls"
    if not os.path.exists(ls):
        return ""
    with open(ls, "r", encoding="utf-8") as f2:
        return f2.read()


# 写入ip到缓存
def set_tag(tag_file, ip):
    with open("/tmp/" + tag_file + ".ls", "w", encoding="utf-8") as f2:
        f2.write(ip)


# 执行更新逻辑
def do_ipv(tag, ip, ips_items):
    if get_tag(tag) == ip:
        print("%s unchanged: %s" % (tag, ip))
        return False
    request = DescribeSubDomainRecordsRequest()
    request.set_accept_format('json')
    for domain, subDomain in ips_items:
        request.set_DomainName(domain)
        for sub in subDomain:
            if tag == "ipv4":
                set_ipv4(request, domain, sub, ip)
            elif tag == "ipv6":
                set_ipv6(request, domain, sub, ip)
    set_tag(tag, ip)


if ipv4_flag == 1:
    ip = urlopen('https://api-ipv4.ip.sb/ip').read()  # 使用IP.SB的接口获取ipv4地址
    ipv4 = str(ip, encoding='utf-8')
    do_ipv("ipv4", ipv4, ipv4s_items)

if ipv6_flag == 1:
    ip = urlopen('https://api-ipv6.ip.sb/ip').read()  # 使用IP.SB的接口获取ipv6地址
    ipv6 = str(ip, encoding='utf-8')
    do_ipv("ipv6", ipv6, ipv6s_items)
